# _*_ coding: utf-8 _*_
__author__ = 'yinlei'
__date__ = '2018-05-18 8:23'

from flask import (
    Blueprint,
    render_template,
    views,
    request,
    session,
    redirect,
    url_for,
    g,
    jsonify,
)


from apps.cms.forms import LoginForm, AddBannersForm, updateBannersForm, UpdateBoardForm, DeleteBoardForm
from apps.cms.forms import ResetpwdForm, ResetEmailform, AddBoardForm
from apps.cms.models import CMSUser, CMSPermission
from apps.models import Banner,BoardModel,PostModel,HighlightPostModel
from config import CMS_USER_ID
from exts import db
from utils import email as email_validate
from tasks import send_mail
from utils import restful, zlcache
import qiniu
from .decorators import login_required, permission_required


cms_route = Blueprint('cms', __name__, url_prefix='/cms')


@cms_route.route('/')
@login_required
def index():
    return render_template('cms/cms_index.html')


@cms_route.route('/logout')
@login_required
def logout():
    session.pop(CMS_USER_ID, None)
    return redirect(url_for('cms.login'))


@cms_route.route('/profile')
@login_required
def profile():
    return render_template('cms/cms_profile.html')

@cms_route.route('/email_captcha/')
@login_required
def email_captcha():
    #celery -A tasks.celery worker --pool=solo --loglevel=info
    email = request.args.get('email')
    if not email or not email_validate.validateEmail(email):
        return restful.params_error('请正确填写邮箱')
    else:
        captcha = email_validate.random_string(6)
        rsult=send_mail.delay('爱派森学院',[email,], body='您的邮箱验证码{}'.format(captcha))
        print(rsult)
        zlcache.set(email,captcha)
        return restful.success('发送成功')


@cms_route.route('/param/<string:name>')
@login_required
def param(name):
    return name


@cms_route.route('/banners/')
@permission_required(CMSPermission.POSTER)
def banners():
    banners = Banner.query.filter_by().order_by(Banner.priority.desc(), Banner.create_time.desc()).all()
    return render_template('cms/cms_banners.html', banners=banners)


@cms_route.route('/add_banners/', methods=['POST'])
@permission_required(CMSPermission.POSTER)
def add_banners():
    form = AddBannersForm(request.form)
    if form.validate():
        name = form.name.data
        image_url = form.image_url.data
        link_url = form.link_url.data
        priority = form.priority.data
        with db.auto_commit():
            banner = Banner(name=name, image_url=image_url, link_url=link_url, priority=priority)
            db.session.add(banner)
        return restful.success('轮播图添加成功')


    else:
        return restful.params_error(message=form.get_error())


@cms_route.route('/update_banner/', methods=['POST'])
@permission_required(CMSPermission.POSTER)
def update_banner():
    form = updateBannersForm(request.form)
    if form.validate():
        banner_id = form.banner_id.data
        banner = Banner.query.get(banner_id)
        if banner:
            name = form.name.data
            image_url = form.image_url.data
            link_url = form.link_url.data
            priority = form.priority.data
            with db.auto_commit():
                banner.name = name
                banner.image_url = image_url
                banner.link_url = link_url
                banner.priority = priority
            return restful.success(message='修改数据成功')

        else:
            return restful.params_error(message='没有这个banner')

    else:
        return restful.params_error('参数错误')


@cms_route.route('/delete_banner/', methods=['POST'])
@permission_required(CMSPermission.POSTER)
def delete_banner():
    banner_id = request.form.get('banner_id')
    if not banner_id:
        return restful.params_error('请传入轮播图id!')
    banner = Banner.query.get(banner_id)
    if not banner:
        return restful.params_error(message='没有这个轮播图')
    with db.auto_commit():
        banner.is_delete=0
    return restful.success(message='删除成功')


@cms_route.route('/uptoken/',methods=['GET','POST'])
def uptoken():
    access_key = 'xaqkINT5fFcwMzJXze0hE9H-CP_ScYvoPhJ6udA2'
    secret_key = '2fm5J5f6nNOjhxEsb8G2X7xvny9u3w9i7NCyRke5'
    q = qiniu.Auth(access_key=access_key, secret_key=secret_key)

    bucket = 'flask'
    token = q.upload_token(bucket=bucket)
    return jsonify({'uptoken': token})


@cms_route.route('/posts/')
@permission_required(CMSPermission.POSTER)
def posts():
    post_list = PostModel.query.filter_by().all()
    return render_template('cms/cms_posts.html',post_list=post_list)

@cms_route.route('/hpost/',methods=['POST'])
@permission_required(CMSPermission.POSTER)
def hpost():
    post_id = request.form.get('post_id')
    if not post_id:
        return restful.params_error('请传入帖子id')
    post= PostModel.query.filter_by(is_delete=1,id=post_id).first()
    if not post:
        return restful.params_error('帖子不存在')
    with db.auto_commit():
        high_post =HighlightPostModel(post_id=post_id)
        db.session.add(high_post)
    return restful.success('帖子加精成功')


@cms_route.route('/uhpost/',methods=['POST'])
@permission_required(CMSPermission.POSTER)
def uhpost():
    post_id = request.form.get('post_id');
    if not post_id:
        return restful.params_error('请传入帖子id');
    post= PostModel.query.filter_by(is_delete=1,id=post_id).first();
    if not post:
        return restful.params_error('帖子不存在');
    highlight = post.highlight;
    if highlight:
        with db.auto_commit():
            db.session.delete(highlight);
    else:
        return restful.params_error('帖子取消加精失败');
    return restful.success('帖子取消精华成功')



@cms_route.route('/comments/')
@permission_required(CMSPermission.COMMENTER)
def comments():
    return render_template('cms/cms_comments.html')


@cms_route.route('/boards/')
@permission_required(CMSPermission.BOARDER)
def boards():
    board_modes =BoardModel.query.filter_by().order_by(BoardModel.create_time.desc()).all()
    context = {
        'boards':board_modes
    }
    return render_template('cms/cms_boards.html',**context)


@cms_route.route('/add_boards/', methods=['POST'])
@permission_required(CMSPermission.BOARDER)
def add_boards():
    form = AddBoardForm(request.form)
    if form.validate():
        name = form.name.data
        with db.auto_commit():
            boardModel = BoardModel(name=name)
            db.session.add(boardModel)
        return restful.success('添加成功')
    else:
        return restful.params_error('参数错误')

@cms_route.route('/update_board/',methods=['POST',])
@permission_required(CMSPermission.BOARDER)
def update_board():
    update_board_form=UpdateBoardForm(request.form)
    if update_board_form.validate():
        id = update_board_form.id.data
        name = update_board_form.name.data
        board=BoardModel.query.get(id)
        if board:
            with db.auto_commit():
                board.name = name
            return restful.success(message='修改成功')
        else:
            return restful.params_error(message='模块不存在')
    else:
        return restful.params_error(message='参数错误')

@cms_route.route('/delete_board/',methods=['POST',])
@permission_required(CMSPermission.BOARDER)
def delete_board():
    form=DeleteBoardForm(request.form)
    if form.validate():
        id = form.id.data
        board =BoardModel.query.get(id)
        if board:
            with db.auto_commit():
                board.is_delete = 0
                return restful.success(message='删除成功')
        else:
            return restful.params_error(message='模块不存在')

    else:
        return restful.params_error(message='参数错误')


@cms_route.route('/fusers/')
@permission_required(CMSPermission.FRONTUSER)
def fusers():
    return render_template('cms/cms_fusers.html')


@cms_route.route('/cusers/')
@permission_required(CMSPermission.CMSUSER)
def cusers():
    return render_template('cms/cms_cusers.html')


@cms_route.route('/croles/')
@permission_required(CMSPermission.ALL_PERMISSION)
def croles():
    return render_template('cms/cms_croles.html')


class ResePwdView(views.MethodView):
    """
    修改密码模块
    """
    methods = ['GET', "POST"]  # 接受的请求方法
    decorators = [login_required, ]  # 装饰器

    def get(self):
        return render_template('cms/cms_resetpwd.html')

    def post(self):

        form = ResetpwdForm(request.form)
        if form.validate():
            oldpwd = form.oldpwd.data
            newpwd = form.newpwd.data
            user = g.cms_user
            if user.check_pwd(oldpwd):
                with db.auto_commit():
                    user.password = newpwd
                return restful.success('修改成功')
            else:
                return restful.params_error('旧密码不对')

        else:
            message = form.get_error()
            return restful.params_error(message)


class LoginView(views.MethodView):
    methods = ['get', 'post']

    def fill_message(self, message):
        return render_template('cms/cms_login.html', message=message)

    def get(self):
        return self.fill_message(None)

    def post(self):
        form = LoginForm(request.form)
        email = form.email.data
        password = form.password.data
        remember = form.remember.data
        if form.validate():
            user = CMSUser.query.filter_by(email=email).first()
            if user and user.check_pwd(password):
                session[CMS_USER_ID] = user.id
                if remember:
                    session.permanent = True
                return redirect(url_for('cms.index'))
            else:

                return self.fill_message(message={'error': '用户名或密码错误', 'email': email})
        else:
            error = form.get_error()
            return self.fill_message(message={'error': error, 'email': email})


class ResetEmailView(views.MethodView):
    methods = ['GET', 'POST']
    decorators = [login_required, ]

    def get(self):
        return render_template('cms/cms_resetemail.html')

    def post(self):
        form = ResetEmailform(request.form)
        if form.validate():
            email = form.email.data
            g.cms_user.email = email
            db.session.commit()
            return restful.success(message='修改成功')
        else:
            return restful.params_error(message=form.get_error())


cms_route.add_url_rule(rule='/login', view_func=LoginView.as_view('login'))
cms_route.add_url_rule('/resetpwd/', view_func=ResePwdView.as_view(name='resetpwd'))
cms_route.add_url_rule(rule='/resetemail/', view_func=ResetEmailView.as_view(name='resetemail'))
